<template>
  <div class="app">
    <div v-show="show">
      <h3>爆品管理</h3>
      <el-form :inline="true" class="demo-form-inline" style="margin-top: 20px;">
        <el-form-item label="搜索">
          <el-input v-model="input" placeholder="请输入标题" clearable></el-input>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="show = !show;title='新增爆品' " style="float: right">
            新增爆品
          </el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" stripe style="width: 100%; text-align: center; margin: 0 auto">
        <el-table-column prop="title" label="名称" width="200" align="center">
        </el-table-column>
        <el-table-column prop="amount" label="数量"  align="center">
        </el-table-column>
        <el-table-column label="图片"  align="center">
          <template slot-scope="scope">
            <div class="block">
              <el-image style="width: 100px; height: 60px" fit="contain"
                        :preview-src-list="[`api/file-load/image-download?name=${scope.row.img}`]"
                        :src="`api/file-load/image-download?name=${scope.row.img}`">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </div>
          </template>

        </el-table-column>
        <el-table-column prop="createTime" label="时间" width="200" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="200" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="230">
          <template slot-scope="scope">
            <el-button
                size="small"
                @click="edit(scope.row)">编辑
            </el-button>
            <el-button size="small" type="warning" @click="update(scope.row)">
              {{ scope.row.status == "禁用" ? "启用" : "禁用" }}
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="del(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
            @current-change="handCurrentChange"
            background
            layout="total,prev, pager, next"
            :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <div v-show="!show">
      <div class="detail" v-show="!show">
        <div class="back">
          <i class="el-icon-arrow-left" @click="back"></i>
        </div>
        <div class="title">
          <i class="el-icon-data-line"></i>
          <span>{{title}}</span>
        </div>

        <!-- 爆品表单 -->

        <el-form
            ref="ruleForm"
            :rules="rules"
            class="product-form"
            label-width="80px"
            style="font-size: 16px"
            :model="formLabel"
        >
          <el-form-item label="产品标题" label-width="100px" prop="title">
            <el-input v-model="formLabel.title"></el-input>
          </el-form-item>
          <el-form-item label="数量" label-width="100px" prop="amount">
            <el-input v-model.number="formLabel.amount"></el-input>
          </el-form-item>
          <el-form-item label="选择日期" label-width="100px" prop="createTime">
            <el-date-picker
                v-model="formLabel.createTime"
                format="yyyy/MM/dd"
                value-format="yyyy/MM/dd"
                type="date"
                placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="展示" label-width="100px">
            <el-switch
                style="text-align: left"
                v-model="formLabel.status"
                active-value="0"
                inactive-value="1"
            ></el-switch>
          </el-form-item>

          <el-form-item label="图片" label-width="100px">
            <el-upload
                ref="upload"
                action="api/file-load/upload"
                list-type="picture-card"
                :file-list="fileList"
                :on-remove="handleRemove"
                :on-change="change"
                :limit="1"
                :class="{ hide: hideUpload }"
                :auto-upload="true"
                :on-success="isSuccess"
            >
              <i slot="default" class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit('ruleForm')">立即创建</el-button>
            <el-button @click="back">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    const checkAmount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('数量不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'));
        } else {

          callback();
        }

      }, 1000);
    };
    return {
      rules: {
        title: [
          {required: true, message: '请输入产品标题', trigger: 'blur'},
        ],
        amount: [
          {required: true, validator: checkAmount, trigger: 'blur'},
        ],
        createTime: [
          {type: 'string', required: true, message: '请选择日期', trigger: 'change'}

        ],
      },
      title:'',
      fileList:[],
      input: '',
      show: true,
      hideUpload: false,
      formLabel: {
        id: "",
        title: "",
        amount: '',
        img: '',
        status: "1",
        createTime: "",
      },
      params: {
        pageNo: "1",
        pageSize: "5",
        name: "",
      },
      total: 0,
      tableData: [],
    };
  },

  methods: {

    edit(row) {
      this.title = "修改爆品"
      this.show = !this.show;
      this.fileList.push({
        'url': `api/file-load/image-download?name=${row.img}`,
      })
      this.hideUpload = !this.hideUpload
      this.formLabel = JSON.parse(JSON.stringify(row))
      // console.log(this.formLabel)
    },
    //跟新
    update(row) {
      row.status == "禁用" ? row.status = "启用" : row.status = "禁用"

      this.$http.put('explosive/update', row)
          .then(res => {
            let code = res.data.code
            if (code == 200) {
              this.$message.success("修改成功")
            }
          })
          .catch(err => {
          })
    },
    //删除
    del(row) {
      this.$http.delete(`explosive/${row.id}`)
          .then(res => {
            let code = res.data.code;
            if (code == 200) {
              this.$message.success("删除成功");
              this.getData();
            }
          })
          .catch(err => {
            console.log(err)
          })
    },
    back() {
      this.show = !this.show;
      this.fileList = []
      this.hideUpload = false
      Object.keys(this.formLabel).forEach(key => (this.formLabel[key] = ''));
      this.formLabel.status = '1'

    },
    //获取数据
    getData() {
      // const axios = axios.create({
      //
      // })
      this.$http.get('explosive/get-explosive', {
        params: this.params
      })
          .then(res => {
            let code = res.data.code;
            if (code === 200) {
              this.tableData = res.data.data.records;
              this.total = res.data.data.total;
            }
          })
          .catch(err => {
            console.log(err)
          })
    },

    // 上传表单以及图片
    async onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formLabel.id > 0) {
            this.$http.put('explosive/update', this.formLabel)
                .then(res => {
                  let code = res.data.code
                  if (code == 200) {
                    this.$message.success("修改成功")
                  }
                })
                .catch(err => {
                  console.log(err)
                })
            setTimeout(() => {
              this.formLabel = {};
              this.back()
            }, 1000)
          } else {
            if (this.formLabel.img === '') {
              this.$message.warning("未上传图片")

            } else {
              this.$http.post("explosive/save", {
                id: this.formLabel.id,
                title: this.formLabel.title,
                amount: this.formLabel.amount,
                img: this.formLabel.img,
                status: this.formLabel.status,
                createTime: this.formLabel.createTime,
              })
                  .then((res) => {
                    // console.log(this.formLabel);
                    let code = res.data.code;
                    if (code === 200) {
                      this.$message.success("保存成功");
                      this.getData();
                    }
                  })
                  .catch((err) => {
                    console.log(err);
                    this.$message.error("内部错误");
                  });
              setTimeout(() => {
                this.formLabel = {};
                this.back()
              }, 1000)
            }
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });

      // await this.$refs.upload.submit();

      // console.log(this.formLabel.img);


      // this.$refs.upload.clearFiles()
    },

    change() {
      this.hideUpload = !this.hideUpload;
    },


    handCurrentChange(val) {
      // console.log(`当前页：${val}`);
      this.params.pageNo = val;
      this.getData();
    },

    isSuccess(res) {
      // console.log(res.data);
      this.formLabel.img = res.data;
      // this.$refs.upload.clearFiles();
      this.hideUpload = !this.hideUpload;
    },

    handleRemove(file) {
      this.hideUpload = !this.hideUpload;

      // console.log(file);
    },
  },

  mounted() {
    this.getData();
  }
};
</script>

<style src="../style/explosive.css" scoped>
</style>